<template>
    <n-form class="w-[340px]" ref="formRef" :model="form" :rules="rules" :show-label="false">
        <n-form-item path="username">
            <n-input v-model:value="form.username" :placeholder="type === 'login' ? '用户名/手机号/邮箱' : '用户名'" />
        </n-form-item>

        <n-form-item path="password">
            <n-input type="password" show-password-on="mousedown" v-model:value="form.password" placeholder="密码" />
        </n-form-item>

        <n-form-item v-if="type === 'reg'" path="repassword">
            <n-input type="password" show-password-on="mousedown" v-model:value="form.repassword" placeholder="确认秘密" />
        </n-form-item>

        <div class="w-full flex justify-between mb-2">
            <n-button type="primary" quaternary size="tiny" @click="changeType">
                {{ type === "login" ? "注册" : "登录" }}
            </n-button>

            <nuxt-link to="/forget">
                <n-button type="primary" quaternary size="tiny" @click="">忘记密码?</n-button>
            </nuxt-link>

        </div>

        <div class="">
            <n-button class="w-full" type="primary" @click="onSubmit" :loading="loading">
                {{ type === "login" ? "登 录" : "注 册" }}
            </n-button>
        </div>

        <div class="flex justify-center items-center w-full text-xs mt-5 text-gray-500">
            注册即同意
            <n-button quaternary type="primary" size="tiny">《服务协议》</n-button>
            和
            <n-button quaternary type="primary" size="tiny">《隐私政策》</n-button>
        </div>
    </n-form>
</template>

<script setup>


// 引入CompositionAPI
import { ref, reactive, computed } from "vue";

// 引入 naive-ui 组件
import { NButton, NInput, NForm, NFormItem, createDiscreteApi } from "naive-ui";

// 路由实例
const route = useRoute();

// formRef 实例
const formRef = ref();

// 类型
const type = ref("login");

// 标题
const title = ref("登录");

// 加载中
const loading = ref(false);

// 响应式数据
const form = reactive({
    username: "",
    password: "",
    repassword: ""
});

// 规则
const rules = computed(() => {
    let r = {
        username: [
            {
                required: true,
                message: type === 'login' ? '用户名/手机号/邮箱' : '用户名'
            },
        ],
        password: [
            {
                required: true,
                message: '密码'
            }
        ]
    }

    if (type.value === 'reg') {
        r.repassword = [
            {
                required: true,
                message: '密码'
            },
            {
                validator: (rule, value) => {
                    return value === form.password;
                },
                message: "两次密码不相同",
                trigger: ['input', 'blur']
            }
        ]
    }
    return r;
})

// 提交表单
const onSubmit = () => {
    formRef.value.validate(async (error) => {
        if (!error) {

            loading.value = true;
            console.log("提交成功")
            const { data, error } = type.value === "login" ? await useLoingApi(form) : await useRegApi(form)
            loading.value = false;

            if (error.value) return

            // 提示实例
            const { message } = createDiscreteApi(['message'])
            message.success(type.value === "login" ? '登录成功' : '注册成功')


            if (type.value === "login") {
                // 将用户登录成功返回的token存储在cookie中，用户登录成功标识
                const token = useCookie("token");
                token.value = data.value.token;

                // 用户全局信息存放
                const user = useUser();
                user.value = data.value;

                // 跳转
                navigateTo(route.query.from || "/", { replace: true })
            } else {

                changeType();
            }

        };
    })
}

// 切换类型
const changeType = () => {
    type.value = type.value === "login" ? "reg" : "login";
    title.value = type.value === "login" ? "登录" : "注册";
    route.meta.title = title.value;
    form.username = "";
    form.password = "";
    form.repassword = "";

    // 还原到未校验的状态
    formRef.value.restoreValidation();
}


// 回车事件
useEnterEvent(() => onSubmit());



// 导航栏标题
useHead({
    title
})

// 为你的页面组件定义元数据。
definePageMeta({
    layout: "login",
    middleware: ["only-visitor"]
});
</script>

<style>
/* .form{
    @apply w-[340px];
} */
</style>